package com.aaa.vegetablemarketexpress.controller;

import com.aaa.vegetablemarketexpress.entity.ShoppingCart;
import com.aaa.vegetablemarketexpress.entity.User;
import com.aaa.vegetablemarketexpress.service.ShoppingCartService;
import com.aaa.vegetablemarketexpress.util.Result;
import com.aaa.vegetablemarketexpress.util.ResultUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @FileName: ShoppingCartController
 * @Description:
 * @Author: 张钰哲
 * @CreateTime: 2025/9/18 10:35
 * @Version: 1.0.0
 */
@RestController
@RequestMapping("shoppingCart")
public class ShoppingCartController {
    @Resource
    private ShoppingCartService shoppingCartService;
    @Resource
    private HttpSession session;

    /**
     * 添加购物车商品记录（需登录，通过Session获取userId）
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public Result addToCart(@RequestBody ShoppingCart shoppingCart) {
        User userInfo = (User) session.getAttribute("userInfo");
        if (userInfo == null) {
            return ResultUtil.failed("用户未登录，请先登录");
        }
        return ResultUtil.success(shoppingCartService.addToCart(shoppingCart));
    }

    /**
     * 查询用户购物车列表
     * @param userId
     * @return
     */
    @GetMapping("/list")
    public Result getCartList(Long userId) {
        User userInfo = (User) session.getAttribute("userInfo");
        if (userInfo == null) {
            return ResultUtil.failed("用户未登录，请先登录");
        }
        Long userId1 = userInfo.getUserId();
        List<ShoppingCart> cartList = shoppingCartService.getCartList(userId1);
        return ResultUtil.success(cartList);
    }

    /**
     * 更新购物车商品数量
     * @param param
     * @return
     */
    @PostMapping("/updateCount")
    public Result updateCartItemCount(@RequestBody Map<String, Object> param) {
        Long cartId = Long.valueOf(param.get("cartId").toString());
        Integer productCount = Integer.valueOf(param.get("productCount").toString());
        return shoppingCartService.updateCartItemCount(cartId, productCount);
    }

    /**
     * 删除购物车商品
     * @param param
     * @return
     */
    @PostMapping("/delete")
    public Result deleteCartItem(@RequestBody Map<String, Object> param) {
        Long cartId = Long.valueOf(param.get("cartId").toString());
        return shoppingCartService.deleteCartItem(cartId);
    }

    /**
     * 清空购物车
     * @return
     */
    @PostMapping("/clear")
    public Result clearCart() {
        return shoppingCartService.clearCart();
    }
    /**
     * 查询购物车商品总数量
     */
    @GetMapping("/count")
    public Result getCartItemCount() {
        return shoppingCartService.getCartItemCount();
    }
}
